<template>
  <div class="wrapper">
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>鉴赏管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加鉴赏</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <div class="main-wrapper">
        <div class="side">
          <el-timeline>
            <el-timeline-item
              v-for="(side, index) in sideList"
              :key="side.content"
              :color="index === currSideIndex ? '#409EFF' : ''"
            >
              <a
                :class="[
                  'side-item-title',
                  index === currSideIndex ? 'side-item-title-curr' : ''
                ]"
                :href="'#' + side.href"
                @click="handleClickSide(index)"
                >{{ side.content }}</a
              >
            </el-timeline-item>
          </el-timeline>
        </div>

        <div class="main" ref="content">
          <!-- <div class="progress-wrapper">
            <div class="progress">进度条</div>
          </div> -->

          <el-form
            label-width="80px"
            :model="addForm"
            :rules="addFormRules"
            ref="addFormRef"
          >
            <div class="main-item goods-base-info">
              <div class="title" id="section-0">● 鉴赏基本信息 ●</div>

              <el-form-item label="鉴赏名称" prop="name">
                <el-input
                  v-model="addForm.name"
                  placeholder="请输入鉴赏名称"
                ></el-input>
              </el-form-item>

              <el-form-item label="种类地区" prop="logistics_price">
                <el-select
                  v-model="addForm.places"
                  filterable
                  multiple
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="绑定商品id" prop="goods_id">
                <el-select
                  v-model="addForm.goods_id"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入关键词"
                  :remote-method="handSearchGoodsNameList"
                >
                  <el-option
                    v-for="item in goodsNameList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="市场流行" prop="is_host">
                <!-- v-model="addForm.is_host" -->
                <el-switch
                  v-model="addForm.is_host"
                  active-text="是"
                  inactive-text="否"
                >
                </el-switch>
              </el-form-item>

              <el-form-item label="鉴赏描述" prop="description">
                <Tinymce
                  :height="300"
                  v-model="addForm.description"
                  ref="tinymce"
                ></Tinymce>
              </el-form-item>
            </div>

            <div class="main-item goods-swiper">
              <div class="title" id="section-1">● 轮播图 ●</div>
              <el-image
                class="goods-swiper-image"
                v-for="swiper in addForm.swiperList"
                :src="swiper.url"
                :key="swiper.id"
                @click="handleRemoveSwiper(swiper.id)"
                fit="fit"
              >
              </el-image>
              <el-form-item prop="swiperList">
                <el-upload
                  multiple
                  class="avatar-uploader"
                  :show-file-list="false"
                  action="#"
                  ref="upload"
                  :http-request="handleSwiperUpload"
                >
                  <i class="el-icon-plus avatar-uploader-swiper"></i>
                </el-upload>
                <span class="tips">（建议尺寸 4：3）</span>
              </el-form-item>
            </div>
            <div class="main-item goods-details-info">
              <div class="title" id="section-2">● 鉴赏详细信息 ●</div>

              <el-form-item prop="details">
                <Tinymce
                  :height="800"
                  v-model="addForm.details"
                  ref="tinymce"
                ></Tinymce>
              </el-form-item>
            </div>

            <div class="main-item submit-wrapper" id="section-3">
              <el-button type="primary" @click="handleSubmit">保 存</el-button>
            </div>
          </el-form>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
/* eslint-disable */

import Tinymce from '../tinymce/TinymceComponent.vue'
export default {
  components: {
    Tinymce
  },
  data() {
    const validateArr = (rule, value, callback) => {
      if (value.length === 0) {
        callback(new Error('该参数列表不能为空'))
      } else {
        callback()
      }
    }

    return {
      sideList: [
        {
          content: '鉴赏基本信息',
          href: 'section-0'
        },
        {
          content: '鉴赏轮播图',
          href: 'section-1'
        },
        {
          content: '鉴赏详细信息',
          href: 'section-2'
        },
        {
          content: '提交',
          href: 'section-3'
        }
      ],
      options: [
        {
          value: '广东',
          label: '广东'
        },
        {
          value: '广西',
          label: '广西'
        },
        {
          value: '海南',
          label: '海南'
        },
        {
          value: '四川',
          label: '四川'
        },
        {
          value: '福建',
          label: '福建'
        },
        {
          value: '云南',
          label: '云南'
        }
      ],
      currSideIndex: 0,
      viewportHeight: 0,
      isClick: false,
      swiperFileList: [],
      goodsNameList: [],
      addForm: {
        places: '',
        name: '',
        goods_id: '',
        is_host: false,
        description: '',
        swiperList: [],
        details: ''
      },
      addFormRules: {
        name: [
          {
            required: true,
            message: '请输入商品名称',
            trigger: 'blur'
          }
        ],
        description: [
          {
            required: true,
            message: '请输入商品描述',
            trigger: 'blur'
          }
        ],
        count: [
          {
            required: true,
            message: '请输入商品库存',
            trigger: 'blur'
          }
        ],

        swiperList: [
          {
            required: true,
            message: '请添加商品轮播图',
            validator: validateArr,
            trigger: 'blur'
          }
        ],

        details: [
          {
            required: true,
            message: '请输入商品详细信息',
            trigger: 'blur'
          }
        ]
      }
    }
  },

  mounted() {
    this.$nextTick(() => {
      let tox = document.querySelector('.tox')
      tox.style.setProperty('z-index', '0', 'important')

      this.viewportHeight = window.innerHeight
      // console.log(this.viewportHeight)
      // 添加窗口大小变化监听
      window.addEventListener('resize', this.handleResize)
      const scrollContainer = this.findScrollParent(this.$refs.content)
      this.scrollContainer = scrollContainer
      this.scrollContainer.addEventListener('scroll', this.handleScroll)
    })
  },
  beforeDestroy() {
    this.scrollContainer.removeEventListener('scroll', this.handleScroll)
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    handleScroll() {
      this.sideList.forEach((_, index) => {
        const section = document.querySelector('#section-' + index)
        // console.log(section)

        const distance = section.getBoundingClientRect().top
        // console.log('距离视口顶部的距离：', distance, '--', index)
        if (distance <= parseInt(this.viewportHeight / 2) && !this.isClick) {
          this.currSideIndex = index
        }
      })
    },

    handleResize() {
      this.viewportHeight = window.innerHeight
    },

    findScrollParent(el) {
      let parent = el
      while (parent) {
        // console.log('aaa')
        const style = window.getComputedStyle(parent)
        const overflowY = style.overflowY
        const canScroll = overflowY === 'scroll' || overflowY === 'auto'
        if (canScroll && parent.scrollHeight > parent.clientHeight) {
          // console.log('🟢 找到可滚动容器:', parent)
          return parent
        }
        parent = parent.parentElement
      }
      return window // fallback
    },

    extractBlobUrls(html) {
      const regex = /<img[^>]*src=["'](blob:[^"'>]*)["'][^>]*>/gi
      const blobUrls = []
      let match

      while ((match = regex.exec(html))) {
        if (match[1]) {
          blobUrls.push(match[1])
        }
      }
      return blobUrls
    },

    async blobUrlToFile(blobUrl, fileName) {
      const response = await fetch(blobUrl)
      const blob = await response.blob()
      return new File([blob], fileName, { type: blob.type })
    },

    handleSubmit() {
      let formData = new FormData()
      this.$refs.addFormRef.validate(async (valid) => {
        // if (!valid) return
        // 获取商品详细信息中的图片，去除删除的图片
        const urls = this.extractBlobUrls(this.addForm.details)

        for (let i = 0; i < urls.length; i++) {
          const file = await this.blobUrlToFile(urls[i], `file${i}.png`)
          formData.append('details[]', file)
        }

        // 处理goods_id
        this.addForm.goods_id = parseInt(this.addForm.goods_id)

        // 添加formdata
        formData.append('enjoy', JSON.stringify(this.addForm))

        // 添加轮播图
        for (let s = 0; s < this.swiperFileList.length; s++) {
          formData.append('swiperList[]', this.swiperFileList[s].file)
        }

        // console.log(this.addForm)

        const { data: res } = await this.$http.post('/saveEnjoy', formData)
        if (res.status !== 200) {
          this.$message.error(res.message)
          return
        }

        this.$message.success(res.message)
        this.resetFormValue()
        // window.scrollTo({
        //   top: 0,
        //   behavior: 'smooth' // 平滑滚动
        // })
        // console.log(contentTempFile)
        // console.log(valid)
      })
    },

    resetFormValue() {
      this.addForm = {
        places: '',
        name: '',
        goods_id: '',
        is_host: false,
        description: '',
        swiperList: [],
        details: ''
      }

      this.swiperFileList = []
    },

    async handSearchGoodsNameList(e) {
      const { data: res } = await this.$http.get('/getGoodsNameList?query=' + e)

      if (res.status !== 200) {
        this.$message.error(res.message)
        return
      }

      this.goodsNameList = res.data.data
    },

    handleSwiperUpload(e) {
      // console.log(e)
      const singleSwiper = e.file
      const url = URL.createObjectURL(singleSwiper)
      this.addForm.swiperList.push({
        id: singleSwiper.uid,
        url: url
      })
      // 先使用数组存储文件，原因是可用指定位置删除元素
      this.swiperFileList.push({
        id: singleSwiper.uid,
        file: singleSwiper
      })
      // console.log(singleSwiper, this.swiperFileList)
      // this.formData.append('swiperList[]', singleSwiper)
    },
    handleRemoveSwiper(id) {
      console.log(id)
      this.$confirm('是否移除该轮播图?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.removeSwiperById(id)

          this.$message({
            type: 'success',
            message: '移除成功!'
          })
        })
        .catch(() => {})
    },
    removeSwiperById(id) {
      const index = this.swiperFileList.findIndex(
        (swiper) => String(swiper.id) === String(id)
      )
      this.swiperFileList.splice(index, 1)
      const index2 = this.addForm.swiperList.findIndex(
        (swiper) => String(swiper.id) === String(id)
      )
      this.addForm.swiperList.splice(index2, 1)
    },
    handleClickSide(index) {
      this.currSideIndex = index
      this.isClick = true
      setTimeout(() => {
        this.isClick = false
      }, 100)
    }
  }
}
</script>

<style lang="less" scoped>
a {
  text-decoration: none;
  color: #909399;
}

.tox {
  z-index: 100 !important;
}

.wrapper {
  .main-wrapper {
    display: flex;
    justify-content: flex-start;

    .side {
      width: 200px;
      padding: 30px;
      padding-top: 100px;
      // background-color: aqua;
      position: relative;
      min-height: 100vh;
      :deep(.el-timeline) {
        position: fixed;
      }

      :deep(.el-timeline-item) {
        cursor: pointer;
      }

      .side-item-title {
        display: block;
        // padding-top: 30px;
        font-size: 17px;
        height: 60px;
        // background-color: aqua;
        // color: red;
      }
      .side-item-title-curr {
        font-size: 23px;
        color: #409eff;
      }
    }

    .main {
      padding: 20px;
      padding-top: 0%;
      box-sizing: border-box;
      position: relative;
      flex: 1;
      // background-color: aquamarine;

      .main-item {
        margin-top: 20px;
        // min-height: 500px;
        padding: 20px;
        box-sizing: border-box;
        width: 100%;

        .title {
          font-size: 25px;
          text-align: center;
          margin-bottom: 20px;
          // color: #909399;
        }
      }

      .avatar-uploader :deep(.el-upload) {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
      }
      .avatar-uploader :deep(.el-upload):hover {
        border-color: #409eff;
      }

      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 100px;
        height: 100px;
        line-height: 100px;
        text-align: center;
      }
      .avatar-uploader-swiper {
        font-size: 28px;
        color: #8c939d;
        width: 200px;
        height: 150px;
        line-height: 150px;
        text-align: center;
      }
      .avatar {
        width: 100px;
        height: 100px;
        display: block;
      }

      .swiper {
        width: 200px;
        height: 150px;
        display: block;
      }

      .goods-swiper-image {
        width: 200px;
        height: 150px;
        margin: 10px;
        position: relative;
        cursor: pointer;

        .delete-swiper {
          position: absolute;
          right: 0%;
          top: 0%;
          width: 30px;
          height: 30px;
          background-color: #409eff;
          z-index: 1;
        }
      }

      .tips {
        color: red;
      }
    }
  }
}

.submit-wrapper {
  text-align: center;
}
</style>
